package com.nie.orderfood.service.impl;

import com.nie.orderfood.DTO.CartDTO;
import com.nie.orderfood.entity.ProductInfo;
import com.nie.orderfood.enums.ProductStatusEnum;
import com.nie.orderfood.enums.ResultEnum;
import com.nie.orderfood.exception.SellException;
import com.nie.orderfood.repository.ProductInfoRepository;
import com.nie.orderfood.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @program: orderfood
 * @description: 商品详情Service
 * @author: NieMiao
 * @create: 2018-10-08 10:05
 **/
@Service
public class ProductInfoServiceImpl implements ProductInfoService {

    @Autowired
    private ProductInfoRepository productInfoRepository;

    @Override
    public List<ProductInfo> findAllUp() {
        return productInfoRepository.findAllByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public ProductInfo findByProductId(String id) {
        return productInfoRepository.findByProductId(id);
    }


    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoRepository.save(productInfo);
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return productInfoRepository.findAll(pageable);
    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO: cartDTOList) {
            ProductInfo product = productInfoRepository.findByProductId(cartDTO.getProductId());
            if (product == null) {
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            int i = product.getProductStock() - cartDTO.getProductQuantity();
            if (i<0) {
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            product.setProductStock(i);
            productInfoRepository.save(product);
        }
    }

    @Override
    @Transactional
    public void increaseStock(List<CartDTO> cartDTOList) {

        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo product = productInfoRepository.findByProductId(cartDTO.getProductId());
            if (product == null) {
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            product.setProductStock(cartDTO.getProductQuantity() + product.getProductStock());
            productInfoRepository.save(product);
        }
    }
}
